const express=require('express')
const CryptoJs=require('crypto-js')
const AdminModel=require('../models/admin')

const router=express.Router()

router.get('/:_id?', (req, res, next) => {
    
})
//用户注册
router.post('/', (req, res, next) => {
    const {username, password, nickname}=req.body
    //判断数据库中是否存在请求的用户
    AdminModel.find({username}).then(data=>{
        if(data.length>0){
            res.json({
                code:200,
                data:{
                    status:400,
                    message:"用户名已被占用，请重新注册！",
                    userInfo:null
                }
            })
            return
        }
        //不存在则对密码进行加密并注册用户
        const hash=CryptoJs.MD5(password)
        const admin = new AdminModel({username, password: hash, nickname})
        admin.save().then(data=>{
            const userInfo={...data._doc}
            //将密码删除返回注册用户信息到客户端
            delete userInfo.password
            res.json({
                code:200,
                data:{
                    status:200,
                    message:"注册成功！",
                    userInfo
                }
            })
        })
    })
})
//修改管理员信息
router.put('/:username', (req, res, next) => {
    const {username}=req.params
    const {password,nickname}=req.body
    const hash=CryptoJs.MD5(password)
    AdminModel.updateOne({username},{password:hash.toString(),nickname}).then(data=>{
        if(data.modifiedCount!==0){
            res.json({
                code:200,
                data:{
                    status:200,
                    message:"修改成功！"
                }
            })
        }
        res.json({
            code:200,
            data:{
                status:400,
                message:"未修改任何数据！"
            }
        })
    })
})
router.delete('/:_id', (req, res, next) => {
   
})

module.exports=router